package com.ssy.lingxi.member.merchant.serviceimpl.web;

import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.constant.member.MemberLevelTypeEnum;
import com.ssy.lingxi.common.constant.member.MemberStatusEnum;
import com.ssy.lingxi.common.constant.member.MemberTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.constant.MemberRelationTypeEnum;
import com.ssy.lingxi.member.merchant.config.ServiceConfig;
import com.ssy.lingxi.member.merchant.entity.*;
import com.ssy.lingxi.member.merchant.model.bo.AuthBO;
import com.ssy.lingxi.member.merchant.model.bo.ButtonBO;
import com.ssy.lingxi.member.merchant.model.bo.WorkflowTaskListBO;
import com.ssy.lingxi.member.merchant.model.bo.WorkflowTaskResultBO;
import com.ssy.lingxi.member.merchant.model.constant.*;
import com.ssy.lingxi.member.merchant.model.vo.basic.response.*;
import com.ssy.lingxi.member.merchant.model.vo.maintenance.response.PlatformMemberQuerySearchConditionVO;
import com.ssy.lingxi.member.merchant.model.vo.maintenance.response.PlatformPageQueryMemberVO;
import com.ssy.lingxi.member.merchant.model.vo.validate.request.*;
import com.ssy.lingxi.member.merchant.model.vo.validate.response.PlatformMemberValidateDetailVO;
import com.ssy.lingxi.member.merchant.model.vo.validate.response.PlatformMemberValidateQueryButtonVO;
import com.ssy.lingxi.member.merchant.model.vo.validate.response.WorkFlowStepVO;
import com.ssy.lingxi.member.merchant.repository.BaseLevelConfigRepository;
import com.ssy.lingxi.member.merchant.repository.MemberRelationRepository;
import com.ssy.lingxi.member.merchant.repository.MemberTypeRepository;
import com.ssy.lingxi.member.merchant.repository.RoleRepository;
import com.ssy.lingxi.member.merchant.service.base.*;
import com.ssy.lingxi.member.merchant.service.feign.*;
import com.ssy.lingxi.member.merchant.service.web.IPlatformMemberValidateService;
import com.ssy.lingxi.member.merchant.utils.AuthBOUtils;
import com.ssy.lingxi.member.merchant.utils.NumberUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * 业务平台管理后台 -会员审核接口实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2020-06-28
 */
@Service
public class PlatformMemberValidateServiceImpl implements IPlatformMemberValidateService {
    @Resource
    private IBaseMemberValidateService baseMemberValidateService;

    @Resource
    private IBaseMemberRegisterDetailService baseMemberRegisterDetailService;

    @Resource
    private MemberRelationRepository relationRepository;

    @Resource
    private MemberTypeRepository memberTypeRepository;

    @Resource
    private BaseLevelConfigRepository baseLevelConfigRepository;

    @Resource
    private RoleRepository roleRepository;

    @Resource
    private IBaseMemberHistoryService baseMemberHistoryService;

    @Resource
    private IBaseMemberCacheService memberCacheService;

    @Resource
    private IBaseAuthService baseAuthService;

    @Resource
    private IWorkflowFeignService workflowFeignService;

    @Resource
    private IPayFeignService payFeignService;

    @Resource
    private IReportFeignService reportFeignService;

    @Resource
    private IMessageFeignService messageFeignService;

    @Resource
    private ILogisticsFeignService logisticsFeignService;

    /**
     * 点击左侧权限菜单，获得右侧按钮列表，以及需要勾选的按钮id列表
     * @param headers HttpHeaders信息
     * @param buttonVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PlatformMemberValidateQueryButtonVO> getTreeAuthButtons(HttpHeaders headers, MemberValidateButtonVO buttonVO) {
        //检验是否使用平台后台账号登录
        memberCacheService.needLoginFromManagePlatform(headers);

        MemberRelationDO relationDO = relationRepository.findById(buttonVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getSubMemberId().equals(buttonVO.getMemberId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }


        RoleDO roleDO = relationDO.getSubRole();
        if(roleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        AuthBO authBO = roleDO.getRoleAuth().getAuth().stream().filter(m -> m.getId().equals(buttonVO.getMenuId())).findFirst().orElse(null);

        if(authBO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
        }
        List<AuthTreeButtonVO> buttonList = authBO.getButtons().stream().map(b -> new AuthTreeButtonVO(b.getButtonId(), b.getTitle())).collect(Collectors.toList());

        List<Long> checkIds = new ArrayList<>();
        if(!CollectionUtils.isEmpty(relationDO.getRelationAuth().getAuth())) {
            AuthBO validateAuthBO = relationDO.getRelationAuth().getAuth().stream().filter(m -> m.getId().equals(buttonVO.getMenuId())).findFirst().orElse(null);
            if(validateAuthBO != null) {
                checkIds = validateAuthBO.getButtons().stream().map(ButtonBO::getButtonId).collect(Collectors.toList());
            }
        }

        PlatformMemberValidateQueryButtonVO queryButtonVO = new PlatformMemberValidateQueryButtonVO();
        queryButtonVO.setButtons(buttonList);
        queryButtonVO.setCheckIds(checkIds);

        return Wrapper.success(queryButtonVO);
    }

    /**
     * 获得左侧全量菜单
     * @param headers HttpHeaders信息
     * @param validateVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<List<AuthTreeMenuVO>> getTreeAuthMenu(HttpHeaders headers, MemberValidateVO validateVO) {
        //检验是否使用平台后台账号登录
        memberCacheService.needLoginFromManagePlatform(headers);

        MemberRelationDO relationDO = relationRepository.findById(validateVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getSubMemberId().equals(validateVO.getMemberId()) || !relationDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        RoleDO roleDO = relationDO.getSubRole();
        if(roleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        return Wrapper.success(AuthBOUtils.transferToTree(roleDO.getRoleAuth().getAuth()));
    }

    /**
     * 获得左侧菜单勾选的Id列表
     *
     * @param validateVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<AuthTreeMenuButtonCheckIdVO> getValidateAuthTreeCheckIds(HttpHeaders headers, MemberValidateVO validateVO) {
        //检验是否使用平台后台账号登录
        memberCacheService.needLoginFromManagePlatform(headers);

        MemberRelationDO relationDO = relationRepository.findById(validateVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getSubMemberId().equals(validateVO.getMemberId()) || !relationDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        AuthTreeMenuButtonCheckIdVO checkIdVO = new AuthTreeMenuButtonCheckIdVO();
        if(CollectionUtils.isEmpty(relationDO.getRelationAuth().getAuth())) {
            checkIdVO.setCheckIds(new ArrayList<>());
        } else {
            checkIdVO.setCheckIds(relationDO.getRelationAuth().getAuth().stream().map(AuthBO::getId).collect(Collectors.toList()));
        }

        return Wrapper.success(checkIdVO);
    }

    /**
     * 修改审核会员的左侧菜单权限
     * @param headers HttpHeaders信息
     * @param updateVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> updateValidateAuth(HttpHeaders headers, MemberValidateUpdateAuthVO updateVO) {
        //检验是否使用平台后台账号登录
        memberCacheService.needLoginFromManagePlatform(headers);

        MemberRelationDO relationDO = relationRepository.findById(updateVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getSubMemberId().equals(updateVO.getMemberId()) || !relationDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        RoleDO roleDO = relationDO.getSubRole();
        if(roleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        List<AuthBO> authBOList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(updateVO.getMenuIds())) {
            if(!updateVO.getMenuIds().stream().allMatch(menuId -> roleDO.getRoleAuth().getAuth().stream().anyMatch(authBO -> authBO.getId().equals(menuId)))) {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
            }

            authBOList = relationDO.getSubRole().getRoleAuth().getAuth().stream().filter(authBO -> updateVO.getMenuIds().contains(authBO.getId())).collect(Collectors.toList());
        }

        if(AuthBOUtils.listNotEqual(relationDO.getRelationAuth().getAuth(), authBOList)) {
            relationDO.getRelationAuth().setAuth(authBOList);
            relationRepository.saveAndFlush(relationDO);

            //合并会员、下属角色、下属用户的权限
            return baseAuthService.mergeMemberAuthFromRelation(relationDO.getSubMember());
        }

        return Wrapper.success();
    }

    /**
     * 修改审核会员的右侧按钮权限
     *
     * @param updateButtonVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> updateValidateAuthButton(HttpHeaders headers, MemberValidateUpdateAuthButtonVO updateButtonVO) {
        //检验是否使用平台后台账号登录
        memberCacheService.needLoginFromManagePlatform(headers);

        MemberRelationDO relationDO = relationRepository.findById(updateButtonVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getSubMemberId().equals(updateButtonVO.getMemberId()) || !relationDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        RoleDO roleDO = relationDO.getSubRole();
        if(roleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        List<AuthBO> roleAuthBOList = roleDO.getRoleAuth().getAuth();
        if(roleAuthBOList.stream().noneMatch(roleAuth -> roleAuth.getId().equals(updateButtonVO.getMenuId()))) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
        }

        AuthBO roleAuthBO = roleAuthBOList.stream().filter(roleAuth -> roleAuth.getId().equals(updateButtonVO.getMenuId())).findFirst().orElse(null);
        if(roleAuthBO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_AUTH_DOES_NOT_EXIST);
        }

        //这里要复制一份，否则会改变角色的权限
        AuthBO newAuthBO = AuthBOUtils.copy(roleAuthBO);
        if(CollectionUtils.isEmpty(updateButtonVO.getButtonIds())) {
            newAuthBO.getButtons().clear();
        } else {
            if(!updateButtonVO.getButtonIds().stream().allMatch(buttonId -> newAuthBO.getButtons().stream().anyMatch(b -> b.getButtonId().equals(buttonId)))) {
                return Wrapper.fail(ResponseCode.MC_MS_BUTTON_DOES_NOT_EXIST);
            }

            newAuthBO.getButtons().removeIf(button -> !updateButtonVO.getButtonIds().contains(button.getButtonId()));
        }

        List<AuthBO> memberAuthBOList = relationDO.getRelationAuth().getAuth();
        memberAuthBOList.removeIf(memberAuth -> memberAuth.getId().equals(newAuthBO.getId()));
        memberAuthBOList.add(newAuthBO);

        relationDO.getRelationAuth().setAuth(memberAuthBOList);
        relationRepository.saveAndFlush(relationDO);

        //合并会员、下属角色、下属用户的权限
        return baseAuthService.mergeMemberAuthFromRelation(relationDO.getSubMember());
    }

    /**
     * 获取“待提交审核会员”页面中各个查询条件下拉选择框的内容
     *
     * @return 操作结果
     */
    @Override
    public Wrapper<PlatformMemberQuerySearchConditionVO> getToBeCommitPageCondition(HttpHeaders headers) {
        //检验是否使用平台后台账号登录
        memberCacheService.needLoginFromManagePlatform(headers);

        PlatformMemberQuerySearchConditionVO conditionVO = getPageConditionWithoutInnerOuterStatus();
        //内部状态
        List<DropdownItem> itemList = new ArrayList<>();
        itemList.add(new DropdownItem(0, "内部状态(全部)"));
        itemList.add(new DropdownItem(PlatformInnerStatusEnum.TO_BE_COMMIT.getCode(), PlatformInnerStatusEnum.TO_BE_COMMIT.getMsg()));
        conditionVO.setInnerStatus(itemList);

        //外部状态
        itemList = new ArrayList<>();
        itemList.add(new DropdownItem(0, "外部状态(全部)"));
        itemList.add(new DropdownItem(MemberOuterStatusEnum.PLATFORM_VERIFYING.getCode(), MemberOuterStatusEnum.PLATFORM_VERIFYING.getMsg()));
        conditionVO.setOuterStatus(itemList);

        return Wrapper.success(conditionVO);
    }

    /**
     * 分页查询“待提交审核会员”列表
     *
     * @param memberQueryVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<PlatformPageQueryMemberVO>> pageToBeCommitMembers(HttpHeaders headers, PlatformMemberValidateQueryVO memberQueryVO) {
        //检验是否使用平台后台账号登录
        memberCacheService.needLoginFromManagePlatform(headers);
        return Wrapper.success(findBySpecification(PlatformInnerStatusEnum.TO_BE_COMMIT, memberQueryVO));
    }

    /**
     * 获取“提交审核会员”页面会员信息
     *
     * @param validateVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PlatformMemberValidateDetailVO> getToBeCommitMemberDetail(HttpHeaders headers, MemberValidateVO validateVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);
        return findValidateMemberDetail(loginUser, validateVO, PlatformInnerStatusEnum.TO_BE_COMMIT);
    }

    /**
     * 提交审核会员
     * @param headers HttpHeaders信息
     * @param commitVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> commitMemberValidate(HttpHeaders headers, MemberValidateCommitVO commitVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);
        return execValidateStep(loginUser, commitVO, Stream.of(PlatformInnerStatusEnum.TO_BE_COMMIT).collect(Collectors.toList()));
    }

    /**
     * 批量提交审核会员
     *
     * @param headers HttpHeaders信息
     * @param validateVOList 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> batchCommitMemberValidate(HttpHeaders headers, List<MemberValidateVO> validateVOList) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);
        return batchExecValidateStep(loginUser, validateVOList, Stream.of(PlatformInnerStatusEnum.TO_BE_COMMIT).collect(Collectors.toList()));
    }


    /**
     * 获取“待审核会员(一级)”页面中各个查询条件下拉选择框的内容
     *
     * @return 操作结果
     */
    @Override
    public Wrapper<PlatformMemberQuerySearchConditionVO> getToBeValidateStep1PageCondition(HttpHeaders headers) {
        //检验是否使用平台后台账号登录
        memberCacheService.needLoginFromManagePlatform(headers);
        PlatformMemberQuerySearchConditionVO conditionVO = getPageConditionWithoutInnerOuterStatus();
        //内部状态
        List<DropdownItem> itemList = new ArrayList<>();
        itemList.add(new DropdownItem(0, "内部状态(全部)"));
        itemList.add(new DropdownItem(PlatformInnerStatusEnum.TO_BE_VERIFY_STEP1.getCode(), PlatformInnerStatusEnum.TO_BE_VERIFY_STEP1.getMsg()));
        conditionVO.setInnerStatus(itemList);

        //外部状态
        itemList = new ArrayList<>();
        itemList.add(new DropdownItem(0, "外部状态(全部)"));
        itemList.add(new DropdownItem(MemberOuterStatusEnum.PLATFORM_VERIFYING.getCode(), MemberOuterStatusEnum.PLATFORM_VERIFYING.getMsg()));
        conditionVO.setOuterStatus(itemList);

        return Wrapper.success(conditionVO);
    }

    /**
     * 分页查询“待审核会员(一级)”列表
     *
     * @param memberQueryVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<PlatformPageQueryMemberVO>> pageToBeValidateStep1Members(HttpHeaders headers, PlatformMemberValidateQueryVO memberQueryVO) {
        memberCacheService.needLoginFromManagePlatform(headers);
        return Wrapper.success(findBySpecification(PlatformInnerStatusEnum.TO_BE_VERIFY_STEP1, memberQueryVO));
    }

    /**
     * 获取“审核会员(一级)”页面会员信息
     *
     * @param validateVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PlatformMemberValidateDetailVO> getValidateStep1MemberDetail(HttpHeaders headers, MemberValidateVO validateVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);
        return findValidateMemberDetail(loginUser, validateVO, PlatformInnerStatusEnum.TO_BE_VERIFY_STEP1);
    }

    /**
     * 审核会员(一级)
     * @param headers HttpHeaders信息
     * @param commitVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> validateMemberStep1(HttpHeaders headers, MemberValidateCommitVO commitVO) {
        //检验是否使用平台后台账号登录
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);
        return execValidateStep(loginUser, commitVO, Stream.of(PlatformInnerStatusEnum.TO_BE_VERIFY_STEP1).collect(Collectors.toList()));
    }

    /**
     * 批量审核会员(一级)
     *
     * @param headers HttpHeaders信息
     * @param validateVOList 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> batchValidateMemberStep1(HttpHeaders headers, List<MemberValidateVO> validateVOList) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);
        return batchExecValidateStep(loginUser, validateVOList, Stream.of(PlatformInnerStatusEnum.TO_BE_VERIFY_STEP1).collect(Collectors.toList()));
    }

    /**
     * 获取“待审核会员(二级)”页面中各个查询条件下拉选择框的内容
     *
     * @return 操作结果
     */
    @Override
    public Wrapper<PlatformMemberQuerySearchConditionVO> getToBeValidateStep2PageCondition(HttpHeaders headers) {
        //检验是否使用平台后台账号登录
        memberCacheService.needLoginFromManagePlatform(headers);
        PlatformMemberQuerySearchConditionVO conditionVO = getPageConditionWithoutInnerOuterStatus();
        //内部状态
        List<DropdownItem> itemList = new ArrayList<>();
        itemList.add(new DropdownItem(0, "内部状态(全部)"));
        itemList.add(new DropdownItem(PlatformInnerStatusEnum.TO_BE_VERIFY_STEP2.getCode(), PlatformInnerStatusEnum.TO_BE_VERIFY_STEP2.getMsg()));
        conditionVO.setInnerStatus(itemList);

        //外部状态
        itemList = new ArrayList<>();
        itemList.add(new DropdownItem(0, "外部状态(全部)"));
        itemList.add(new DropdownItem(MemberOuterStatusEnum.PLATFORM_VERIFYING.getCode(), MemberOuterStatusEnum.PLATFORM_VERIFYING.getMsg()));
        conditionVO.setOuterStatus(itemList);

        return Wrapper.success(conditionVO);
    }

    /**
     * 分页查询“待审核会员(二级)”列表
     *
     * @param memberQueryVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<PlatformPageQueryMemberVO>> pageToBeValidateStep2Members(HttpHeaders headers, PlatformMemberValidateQueryVO memberQueryVO) {
        memberCacheService.needLoginFromManagePlatform(headers);
        return Wrapper.success(findBySpecification(PlatformInnerStatusEnum.TO_BE_VERIFY_STEP2, memberQueryVO));
    }

    /**
     * 获取“审核会员(二级)”页面会员信息
     *
     * @param validateVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PlatformMemberValidateDetailVO> getValidateStep2MemberDetail(HttpHeaders headers, MemberValidateVO validateVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);
        return findValidateMemberDetail(loginUser, validateVO, PlatformInnerStatusEnum.TO_BE_VERIFY_STEP2);
    }

    /**
     * 审核会员(二级)
     * @param headers HttpHeaders信息
     * @param commitVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> validateMemberStep2(HttpHeaders headers, MemberValidateCommitVO commitVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);
        return execValidateStep(loginUser, commitVO, Stream.of(PlatformInnerStatusEnum.TO_BE_VERIFY_STEP2).collect(Collectors.toList()));
    }

    /**
     * 批量审核会员(二级)
     *
     * @param headers HttpHeaders信息
     * @param validateVOList 接口参数List
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> batchValidateMemberStep2(HttpHeaders headers, List<MemberValidateVO> validateVOList) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);
        return batchExecValidateStep(loginUser, validateVOList, Stream.of(PlatformInnerStatusEnum.TO_BE_VERIFY_STEP2).collect(Collectors.toList()));
    }

    /**
     * 获取“待确认会员审核结果”页面中各个查询条件下拉选择框的内容
     *
     * @return 操作结果
     */
    @Override
    public Wrapper<PlatformMemberQuerySearchConditionVO> getToBeConfirmPageCondition(HttpHeaders headers) {
        //检验是否使用平台后台账号登录
        memberCacheService.needLoginFromManagePlatform(headers);
        PlatformMemberQuerySearchConditionVO conditionVO = getPageConditionWithoutInnerOuterStatus();
        //内部状态
        List<DropdownItem> itemList = new ArrayList<>();
        itemList.add(new DropdownItem(0, "内部状态(全部)"));
        itemList.add(new DropdownItem(PlatformInnerStatusEnum.COMMIT_NOT_PASSED.getCode(), PlatformInnerStatusEnum.COMMIT_NOT_PASSED.getMsg()));
        itemList.add(new DropdownItem(PlatformInnerStatusEnum.VERIFY_STEP1_NOT_PASSED.getCode(), PlatformInnerStatusEnum.VERIFY_STEP1_NOT_PASSED.getMsg()));
        itemList.add(new DropdownItem(PlatformInnerStatusEnum.VERIFY_STEP2_NOT_PASSED.getCode(), PlatformInnerStatusEnum.VERIFY_STEP2_NOT_PASSED.getMsg()));
        itemList.add(new DropdownItem(PlatformInnerStatusEnum.TO_CONFIRM.getCode(), PlatformInnerStatusEnum.TO_CONFIRM.getMsg()));
        conditionVO.setInnerStatus(itemList);

        //外部状态
        itemList = new ArrayList<>();
        itemList.add(new DropdownItem(0, "外部状态(全部)"));
        itemList.add(new DropdownItem(MemberOuterStatusEnum.PLATFORM_VERIFYING.getCode(), MemberOuterStatusEnum.PLATFORM_VERIFYING.getMsg()));
        conditionVO.setOuterStatus(itemList);

        return Wrapper.success(conditionVO);
    }

    /**
     * 分页查询“待确认会员审核结果”列表
     *
     * @param memberQueryVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<PlatformPageQueryMemberVO>> pageToBeConfirmMembers(HttpHeaders headers, PlatformMemberValidateQueryVO memberQueryVO) {
        memberCacheService.needLoginFromManagePlatform(headers);
        Integer innerStatus = memberQueryVO.getInnerStatus();
        List<PlatformInnerStatusEnum> innerStatusEnums = (innerStatus == null || innerStatus == 0) ? Stream.of(PlatformInnerStatusEnum.COMMIT_NOT_PASSED, PlatformInnerStatusEnum.VERIFY_STEP1_NOT_PASSED, PlatformInnerStatusEnum.VERIFY_STEP2_NOT_PASSED, PlatformInnerStatusEnum.TO_CONFIRM).collect(Collectors.toList()) : Stream.of(PlatformInnerStatusEnum.parse(innerStatus)).collect(Collectors.toList());
        return Wrapper.success(findBySpecification(innerStatusEnums, memberQueryVO));
    }

    /**
     * 获取“确认会员审核结果”页面会员信息
     *
     * @param validateVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PlatformMemberValidateDetailVO> getConfirmValidateMemberDetail(HttpHeaders headers, MemberValidateVO validateVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);
        List<PlatformInnerStatusEnum> innerStatusEnums = Stream.of(PlatformInnerStatusEnum.COMMIT_NOT_PASSED, PlatformInnerStatusEnum.VERIFY_STEP1_NOT_PASSED, PlatformInnerStatusEnum.VERIFY_STEP2_NOT_PASSED, PlatformInnerStatusEnum.TO_CONFIRM).collect(Collectors.toList());
        return findValidateMemberDetail(loginUser, validateVO, innerStatusEnums);
    }

    /**
     * 确认会员审核结果
     * @param headers HttpHeaders信息
     * @param commitVO 接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> confirmMemberValidate(HttpHeaders headers, MemberValidateCommitVO commitVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);
        return execValidateStep(loginUser, commitVO, Stream.of(PlatformInnerStatusEnum.COMMIT_NOT_PASSED, PlatformInnerStatusEnum.VERIFY_STEP1_NOT_PASSED, PlatformInnerStatusEnum.VERIFY_STEP2_NOT_PASSED, PlatformInnerStatusEnum.TO_CONFIRM).collect(Collectors.toList()));
    }

    /**
     * 批量确认会员审核结果
     *
     * @param headers HttpHeaders信息
     * @param validateVOList 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> batchConfirmMemberValidate(HttpHeaders headers, List<MemberValidateVO> validateVOList) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);
        return batchExecValidateStep(loginUser, validateVOList, Stream.of(PlatformInnerStatusEnum.COMMIT_NOT_PASSED, PlatformInnerStatusEnum.VERIFY_STEP1_NOT_PASSED, PlatformInnerStatusEnum.VERIFY_STEP2_NOT_PASSED, PlatformInnerStatusEnum.TO_CONFIRM).collect(Collectors.toList()));
    }


    /**
     * 构造查询页面下拉菜单内容
     * @return 菜单内容
     */
    private PlatformMemberQuerySearchConditionVO getPageConditionWithoutInnerOuterStatus() {
        PlatformMemberQuerySearchConditionVO conditionVO = new PlatformMemberQuerySearchConditionVO();

        //会员状态
        List<DropdownItem> itemList = new ArrayList<>();
        for(Integer key : MemberStatusEnum.toList()) {
            itemList.add(new DropdownItem(key, MemberStatusEnum.getCodeMessage(key)));
        }
        conditionVO.setStatus(itemList);

        //会员类型
        conditionVO.setMemberTypes(memberTypeRepository.findAll().stream().sorted(Comparator.comparingInt(MemberTypeDO::getTypeEnum)).map(memberTypeDO -> new MemberTypeIdAndNameVO(memberTypeDO.getId(), MemberTypeEnum.getCodeMessage(memberTypeDO.getTypeEnum()))).collect(Collectors.toList()));

        //会员角色（按照Id升序排序）
        conditionVO.setMemberRoles(roleRepository.findAll().stream().filter(r -> !r.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())).map(roleDO -> new RoleIdAndNameVO(roleDO.getId(), roleDO.getRoleName())).sorted(Comparator.comparingLong(RoleIdAndNameVO::getRoleId)).collect(Collectors.toList()));

        //注册来源
        itemList = new ArrayList<>();
        for(Integer key : MemberRegisterSourceEnum.toList()) {
            itemList.add(new DropdownItem(key, MemberRegisterSourceEnum.getCodeMessage(key)));
        }
        conditionVO.setSource(itemList);

        //平台会员的等级
        List<LevelAndTagVO> levelList = baseLevelConfigRepository.findByMemberLevelTypeEnumAndStatus(MemberLevelTypeEnum.PLATFORM.getCode(), EnableDisableStatus.ENABLE.getCode()).stream().map(memberLevelConfigDO -> new LevelAndTagVO(memberLevelConfigDO.getLevel(), memberLevelConfigDO.getLevelTag()))
                .collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(LevelAndTagVO::getLevel))), ArrayList::new))
                .stream().sorted(Comparator.comparing(LevelAndTagVO::getLevel)).collect(Collectors.toList());
        conditionVO.setMemberLevels(levelList);

        return conditionVO;
    }

    /**
     * 分页查询审核会员列表
     * @param innerStatusEnum 内部状态
     * @param queryVO 接口参数
     * @return 查询结果
     */
    private PageData<PlatformPageQueryMemberVO> findBySpecification(PlatformInnerStatusEnum innerStatusEnum, PlatformMemberValidateQueryVO queryVO) {
        return findBySpecification(Stream.of(innerStatusEnum).collect(Collectors.toList()), queryVO);
    }

    /**
     * 分页查询审核会员的列表
     * @param innerStatusEnums 内部状态列表
     * @param queryVO 接口参数
     * @return 查询结果
     */
    private PageData<PlatformPageQueryMemberVO> findBySpecification(List<PlatformInnerStatusEnum> innerStatusEnums, PlatformMemberValidateQueryVO queryVO) {
        Specification<MemberRelationDO> spec = (Specification<MemberRelationDO>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            //平台会员关系
            list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.PLATFORM.getCode()));

            //内部状态
            if(innerStatusEnums.size() == 1) {
                list.add(criteriaBuilder.equal(root.get("innerStatus").as(Integer.class), innerStatusEnums.get(0).getCode()));
            } else {
                Expression<Integer> exp = root.get("innerStatus").as(Integer.class);
                list.add(exp.in(innerStatusEnums.stream().map(PlatformInnerStatusEnum::getCode).collect(Collectors.toList())));
            }

            //注册起始时间
            if(StringUtils.hasLength(queryVO.getStartDate())) {
                LocalDateTime startDate = LocalDateTime.parse(queryVO.getStartDate().concat(" 00:00:00"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime").as(LocalDateTime.class), startDate));
            }

            //注册结束日期
            if(StringUtils.hasLength(queryVO.getEndDate())) {
                LocalDateTime endDate = LocalDateTime.parse(queryVO.getEndDate().concat(" 23:59:59"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                list.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime").as(LocalDateTime.class), endDate));
            }

            //会员角色
            if(NumberUtil.notNullOrZero(queryVO.getRoleId())) {
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), queryVO.getRoleId()));
            }

            //外部状态
            if(NumberUtil.notNullOrZero(queryVO.getOuterStatus())) {
                list.add(criteriaBuilder.equal(root.get("outerStatus").as(Integer.class), queryVO.getOuterStatus()));
            }

            //会员名称
            Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
            if(StringUtils.hasLength(queryVO.getName())) {
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + queryVO.getName().trim() + "%"));
            }

            //注册来源
            if(NumberUtil.notNullOrZero(queryVO.getSource())) {
                list.add(criteriaBuilder.equal(subMemberJoin.get("source").as(Integer.class), queryVO.getSource()));
            }

            //会员等级
            if(NumberUtil.notNullOrZero(queryVO.getLevel())) {
                Join<Object, Object> levelRightJoin = root.join("levelRight", JoinType.LEFT);
                list.add(criteriaBuilder.equal(levelRightJoin.get("level").as(Integer.class), queryVO.getLevel()));
            }

            //会员类型
            if(NumberUtil.notNullOrZero(queryVO.getMemberTypeId())) {
                Join<Object, Object> memberTypeJoin = root.join("subRole", JoinType.LEFT);
                list.add(criteriaBuilder.equal(memberTypeJoin.get("memberType").get("id").as(Long.class), queryVO.getMemberTypeId()));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(queryVO.getCurrent() - 1, queryVO.getPageSize(), Sort.by("id").descending());
        Page<MemberRelationDO> pageList =  relationRepository.findAll(spec, page);

        return new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            PlatformPageQueryMemberVO memberVO = new PlatformPageQueryMemberVO();
            memberVO.setMemberId(relationDO.getSubMember().getId());
            memberVO.setValidateId(relationDO.getId());
            memberVO.setName(relationDO.getSubMember().getName());
            memberVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            memberVO.setRoleId(relationDO.getSubRoleId());
            memberVO.setRoleName(relationDO.getSubRole().getRoleName());
            memberVO.setSource(relationDO.getSubMember().getSource());
            memberVO.setSourceName(MemberRegisterSourceEnum.getCodeMessage(relationDO.getSubMember().getSource()));
            memberVO.setRegisterTime(relationDO.getCreateTime().format(ServiceConfig.DEFAULT_DATETIME_FORMATTER));
            memberVO.setLevel(relationDO.getLevelRight() == null ? 0 : relationDO.getLevelRight().getLevel());
            memberVO.setLevelTag(relationDO.getLevelRight() == null ? "" : relationDO.getLevelRight().getLevelTag());
            memberVO.setStatus(relationDO.getStatus());
            memberVO.setStatusName(MemberStatusEnum.getCodeMessage(relationDO.getStatus()));
            memberVO.setInnerStatus(relationDO.getInnerStatus());
            memberVO.setInnerStatusName(PlatformInnerStatusEnum.getCodeMsg(relationDO.getInnerStatus()));
            memberVO.setOuterStatus(relationDO.getOuterStatus());
            memberVO.setOuterStatusName(MemberOuterStatusEnum.getCodeMsg(relationDO.getOuterStatus()));
            return memberVO;
        }).collect(Collectors.toList()));
    }

    /**
     * 查询审核会员详情
     * @param loginUser 登录用户
     * @param validateVO 接口参数
     * @param innerStatusEnum 平台审核内部状态
     * @return 查询结果
     */
    private Wrapper<PlatformMemberValidateDetailVO> findValidateMemberDetail(UserLoginCacheDTO loginUser, MemberValidateVO validateVO, PlatformInnerStatusEnum innerStatusEnum) {
        return findValidateMemberDetail(loginUser, validateVO, Stream.of(innerStatusEnum).collect(Collectors.toList()));
    }

    /**
     * 查询审核会员详情
     * @param loginUser 登录用户
     * @param validateVO 接口参数
     * @param innerStatusEnums 平台内部审核状态列表
     * @return 操作结果
     */
    private Wrapper<PlatformMemberValidateDetailVO> findValidateMemberDetail(UserLoginCacheDTO loginUser, MemberValidateVO validateVO, List<PlatformInnerStatusEnum> innerStatusEnums) {
        MemberRelationDO relationDO = relationRepository.findById(validateVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getSubMemberId().equals(validateVO.getMemberId()) || !relationDO.getMemberId().equals(loginUser.getMemberId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        //判断审核状态
        if(innerStatusEnums.stream().noneMatch(innerStatusEnum -> innerStatusEnum.getCode().equals(relationDO.getInnerStatus()))) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_VALIDATE_STATUS_INCORRECT);
        }

        MemberDO memberDO = relationDO.getSubMember();
        if(memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        RoleDO roleDO = relationDO.getSubRole();
        if(roleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }


        MemberLevelRightDO levelRightDO = relationDO.getLevelRight();
        PlatformMemberValidateDetailVO detailVO = new PlatformMemberValidateDetailVO();
        detailVO.setOuterVerifySteps(baseMemberValidateService.getPlatformValidateOuterSteps(relationDO.getRole().getRoleName()));
        detailVO.setCurrentOuterStep(2);

        //设置内外审核步骤
        //从工作流服务获得内部审核流程信息
        Wrapper<WorkflowTaskListBO> stepResult = workflowFeignService.listMemberProcessSteps(validateVO.getMemberId(), relationDO.getValidateTask().getProcessKey(), relationDO.getValidateTask().getTaskId());
        if(stepResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(stepResult.getCode(), stepResult.getMessage());
        }

        List<WorkFlowStepVO> innerStepList = stepResult.getData().getStepList().stream().map(s -> {
            WorkFlowStepVO flowStepVO = new WorkFlowStepVO();
            flowStepVO.setStep(s.getStep());
            flowStepVO.setRoleName(s.getRoleName());
            flowStepVO.setStepName(s.getStepName());
            return flowStepVO;
        }).collect(Collectors.toList());
        detailVO.setInnerVerifySteps(innerStepList);
        detailVO.setCurrentInnerStep(stepResult.getData().getCurrentStep());

        //基本信息
        detailVO.setValidateId(relationDO.getId());
        detailVO.setMemberId(memberDO.getId());
        detailVO.setName(StringUtils.hasLength(memberDO.getName()) ? memberDO.getName() : "");
        detailVO.setOuterStatus(relationDO.getOuterStatus());
        detailVO.setOuterStatusName(MemberOuterStatusEnum.getCodeMsg(relationDO.getOuterStatus()));
        detailVO.setInnerStatus(relationDO.getInnerStatus());
        detailVO.setInnerStatusName(PlatformInnerStatusEnum.getCodeMsg(relationDO.getInnerStatus()));
        detailVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(roleDO.getMemberType().getTypeEnum()));
        detailVO.setRoleName(roleDO.getRoleName());
        detailVO.setLevelTag(levelRightDO == null ? "" : levelRightDO.getLevelTag());
        detailVO.setAccount(memberDO.getAccount());
        detailVO.setPhone(memberDO.getPhone());
        detailVO.setEmail(StringUtils.hasLength(memberDO.getEmail()) ? memberDO.getEmail() : "");
        detailVO.setCreateTime(relationDO.getCreateTime().format(ServiceConfig.DEFAULT_DATETIME_FORMATTER));
        detailVO.setStatus(relationDO.getStatus());
        detailVO.setStatusName(MemberStatusEnum.getCodeMessage(relationDO.getStatus()));

        detailVO.setGroups(baseMemberRegisterDetailService.groupMemberRegisterDetailText(memberDO, MemberDetailVersionEnum.TO_BE_VALIDATE));

        //功能权限菜单
        //所有权限以角色的权限为准
        detailVO.setAuths(AuthBOUtils.transferToTree(roleDO.getRoleAuth().getAuth()));
        //勾选的菜单和按钮的id以ValidateDO自身为主
        List<Long> checkMenuIds = CollectionUtils.isEmpty(relationDO.getRelationAuth().getAuth()) ? new ArrayList<>() : relationDO.getRelationAuth().getAuth().stream().map(AuthBO::getId).collect(Collectors.toList());
        detailVO.setCheckMenuIds(checkMenuIds);

        //历史流转记录
        detailVO.setHistory(baseMemberHistoryService.listMemberOuterHistory(relationDO));

        //内部订单流转记录
        detailVO.setInnerHistory(baseMemberHistoryService.listMemberInnerHistory(relationDO));

        return Wrapper.success(detailVO);
    }

    /**
     * 批量执行审核
     * @param loginUser 登录用户
     * @param validateVOList 接口参数
     * @return 审核结果
     */
    public Wrapper<Void> batchExecValidateStep(UserLoginCacheDTO loginUser, List<MemberValidateVO> validateVOList, List<PlatformInnerStatusEnum> innerStatusEnums) {
        if(CollectionUtils.isEmpty(validateVOList)) {
            return Wrapper.fail(ResponseCode.REQUEST_LIST_PARAM_CHECK_FAILED);
        }

        List<Long> relationIds = validateVOList.stream().map(MemberValidateVO::getValidateId).collect(Collectors.toList());
        List<MemberRelationDO> relationList = relationRepository.findAllById(relationIds);
        if(relationIds.size() != relationList.size() || relationList.stream().anyMatch(relationDO -> !relationDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode()))) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        for (MemberRelationDO relationDO : relationList) {
            MemberValidateVO validateVO = validateVOList.stream().filter(v -> v.getValidateId().equals(relationDO.getId())).findFirst().orElse(null);
            if(validateVO == null || !validateVO.getMemberId().equals(relationDO.getSubMemberId()))  {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
            }
        }

        for (MemberRelationDO relationDO : relationList) {
            Wrapper<Void> result = execValidateStep(loginUser, relationDO, MemberValidateAgreeEnum.AGREE.getCode(), "", innerStatusEnums);
            if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
                return result;
            }
        }

        return Wrapper.success();
    }

    /**
     * 执行审核步骤
     * @param loginUser 登录用户信息
     * @param commitVO 接口参数
     * @return 操作结果
     */
    public Wrapper<Void> execValidateStep(UserLoginCacheDTO loginUser, MemberValidateCommitVO commitVO, List<PlatformInnerStatusEnum> innerStatusEnums) {
        MemberRelationDO relationDO = relationRepository.findById(commitVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getSubMemberId().equals(commitVO.getMemberId()) || !relationDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        return execValidateStep(loginUser, relationDO, commitVO.getAgree(), commitVO.getReason(), innerStatusEnums);
    }

    /**
     * 执行审核步骤
     * @param loginUser 登录用户
     * @param relationDO 会员关系
     * @param agree  审核结果
     * @param reason 审核意见
     * @param innerStatusEnums 内部审核状态列表
     * @return 执行结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    public Wrapper<Void> execValidateStep(UserLoginCacheDTO loginUser, MemberRelationDO relationDO, Integer agree, String reason, List<PlatformInnerStatusEnum> innerStatusEnums) {
        //审核不通过原因
        if(agree.equals(MemberValidateAgreeEnum.DISAGREE.getCode()) && !StringUtils.hasLength(reason)) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_VALIDATE_DISAGREE_REASON_CAN_NOT_BE_EMPTY);
        }

        //TaskId如果为空，说明流程已经结束
        if(!StringUtils.hasLength(relationDO.getValidateTask().getTaskId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_VALIDATE_HAS_COMPLETED);
        }

        //检查状态
        if(innerStatusEnums.stream().noneMatch(innerStatusEnum -> innerStatusEnum.getCode().equals(relationDO.getInnerStatus()))) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_VALIDATE_STATUS_INCORRECT);
        }

        //记录执行工作流任务之前的内部状态，用于向报表服务发送消息
        int lastInnerStatus = relationDO.getInnerStatus();
        //调用工作流接口
        Wrapper<WorkflowTaskResultBO> taskResult = workflowFeignService.execMemberProcess(relationDO, agree);
        if(taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        relationDO.getValidateTask().setTaskId(taskResult.getData().getTaskId());
        relationDO.setInnerStatus(taskResult.getData().getInnerStatus());

        //根据返回的taskId是否为空来判断流程是否结束
        if(!StringUtils.hasLength(taskResult.getData().getTaskId())) {
            if(taskResult.getData().getInnerStatus().equals(PlatformInnerStatusEnum.VERIFY_PASSED.getCode())) {
                relationDO.setOuterStatus(MemberOuterStatusEnum.PLATFORM_VERIFY_PASSED.getCode());
                relationDO.setVerified(MemberValidateStatusEnum.VERIFY_PASSED.getCode());
                relationDO.setValidateMsg("");
                relationDO.setDepositTime(LocalDateTime.now());

                //如果审核通过，通知支付服务，新增资金账户
                payFeignService.notifyMemberAssetAccount(relationDO.getMemberId(), relationDO.getMember().getName(), relationDO.getRoleId(), relationDO.getRole().getRoleName(), relationDO.getSubMemberId(), relationDO.getSubMember().getName(), relationDO.getSubRoleId(), relationDO.getSubRoleName(), MemberLevelTypeEnum.PLATFORM.getCode(), relationDO.getSubRole().getMemberType().getTypeEnum(), relationDO.getStatus());
            } else {
                relationDO.setValidateMsg(StringUtils.hasLength(reason) ? reason : "");
                relationDO.setOuterStatus(MemberOuterStatusEnum.PLATFORM_VERIFY_NOT_PASSED.getCode());
            }

            //无论是否审核通过，记录外部历史记录
            baseMemberHistoryService.saveMemberOuterHistory(relationDO, MemberValidateHistoryOperationEnum.parseString(taskResult.getData().getOperation()), reason);

            //无论是否审核通过，更新注册资料版本
            baseMemberRegisterDetailService.updateMemberRegisterDetailToUsing(relationDO.getSubMember());
        }

        relationRepository.saveAndFlush(relationDO);

        // 根据注册来源修改会员能力审核的状态
        Wrapper<Void> updateResult = updateMemberRelationValidateStatus(relationDO.getRole().getRoleName(), relationDO.getRelSource(), relationDO.getOuterStatus(), relationDO.getSubMemberId(), relationDO.getSubRoleId(), reason);
        if(updateResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(updateResult.getCode(), updateResult.getMessage());
        }

        //记录内部操作记录
        baseMemberHistoryService.saveMemberInnerHistory(relationDO, loginUser, MemberValidateHistoryOperationEnum.parseString(taskResult.getData().getOperation()), reason);

        //异步通知报表服务、实时消息服务，物流服务
        reportFeignService.reportPlatformMemberValidate(relationDO.getId(), relationDO.getMemberId(), relationDO.getRoleId(), lastInnerStatus, taskResult.getData().getInnerStatus());
        messageFeignService.sendMemberValidateMessage(relationDO);
        logisticsFeignService.initMemberLogisticsAsync(relationDO);

        return Wrapper.success();
    }

    /**
     * 根据平台会员审核的结果，更新会员能力关系的状态
     *
     * @param platformRelation 平台会员关系
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> updateMemberRelationValidateStatus(MemberRelationDO platformRelation) {
        return updateMemberRelationValidateStatus(platformRelation.getRole().getRoleName(), platformRelation.getRelSource(), platformRelation.getOuterStatus(), platformRelation.getSubMemberId(), platformRelation.getSubRoleId(), "");
    }


    /**
     * 根据平台会员审核的结果，更新会员能力关系的状态
     * @param platformRoleName 平台会员角色名称
     * @param relationSource  平台会员关系的注册来源
     * @param platformOuterStatus 平台会员关系的外部状态
     * @param subMemberId     下级会员Id
     * @param subRoleId       下级角色Id
     * @param reason          平台会员的审核意见
     */
    private Wrapper<Void> updateMemberRelationValidateStatus(String platformRoleName, Integer relationSource, Integer platformOuterStatus, Long subMemberId, Long subRoleId, String reason) {
        if(!relationSource.equals(MemberRelationSourceEnum.MEMBER_CREATE.getCode())) {
            return Wrapper.success();
        }

        if(!platformOuterStatus.equals(MemberOuterStatusEnum.PLATFORM_VERIFY_PASSED.getCode()) && !platformOuterStatus.equals(MemberOuterStatusEnum.PLATFORM_VERIFY_NOT_PASSED.getCode())) {
            return Wrapper.success();
        }

        MemberRelationDO relationDO = relationRepository.findFirstBySubMemberIdAndSubRoleIdAndRelType(subMemberId, subRoleId, MemberRelationTypeEnum.OTHER.getCode());
        if(relationDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        //根据“是否曾经审核通过”来判断，平台会员审核流程是由会员导入功能发起的（需要入库流程），还是由会员信息查询中修改了注册资料后发起的（不需要入库流程）
        if(relationDO.getVerified().equals(MemberValidateStatusEnum.VERIFY_PASSED.getCode())) {
            return Wrapper.success();
        }

        //启动会员入库流程
        Wrapper<WorkflowTaskResultBO> taskResult = workflowFeignService.startMemberProcess(relationDO);
        if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        relationDO.setInnerStatus(taskResult.getData().getInnerStatus());
        relationDO.getValidateTask().setTaskId(taskResult.getData().getTaskId());
        //平台会员审核通过后，会进入到会员入库审核，所以将外部状态置为“待审核会员入库”
        //平台会员审核不通过，将外部状态置为“平台审核不通过”
        relationDO.setOuterStatus(platformOuterStatus.equals(MemberOuterStatusEnum.PLATFORM_VERIFY_PASSED.getCode()) ? MemberOuterStatusEnum.DEPOSITING.getCode() : MemberOuterStatusEnum.PLATFORM_VERIFY_NOT_PASSED.getCode());
        relationRepository.saveAndFlush(relationDO);

        //外部流转记录
        baseMemberHistoryService.saveMemberOuterHistory(relationDO, platformRoleName, MemberValidateHistoryOperationEnum.PLATFORM_VALIDATE, MemberOuterStatusEnum.getCodeMsg(platformOuterStatus), StringUtils.hasLength(reason) ? reason : "");

        //报表统计、实时消息
        reportFeignService.reportMemberValidate(relationDO.getId(), relationDO.getMemberId(), relationDO.getRoleId(), null, taskResult.getData().getInnerStatus(), relationDO.getValidateTask().getProcessTypeEnum());
        messageFeignService.sendMemberValidateMessage(relationDO);

        return Wrapper.success();
    }
}
